/*
 * i2c_ops.c
 *
 *  Created on: 2021-2-7
 *      Author: Administrator
 */
#include <stdint.h>
#include <hw/i2c.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
/***************************************************************** I2C_RD() ***/
int
i2c_rd(int fd, uint32_t dev_addr, uint8_t reg_addr, uint8_t *data)
{
	struct send_recv
	{
		i2c_sendrecv_t hdr;
		uint8_t buf[2];
	} i2c_data;

	int error = EOK;
	int retry, timeout = 10;

	i2c_data.buf[0] = reg_addr;
	i2c_data.hdr.send_len = 1;
	i2c_data.hdr.recv_len = 1;
	i2c_data.hdr.slave.addr = dev_addr;
	i2c_data.hdr.slave.fmt = I2C_ADDRFMT_7BIT;
	i2c_data.hdr.stop = 1;

	/* Retry writing data through I2C */
	for (retry = 0; retry < timeout; retry++) {
		error = devctl(fd, DCMD_I2C_SENDRECV, &i2c_data, sizeof (i2c_data), NULL);
		if(error != EOK) {
			delay(5);
		} else {
			break;
		}
	}
	if (retry >= timeout) {
		logmsg( "%s failed,  dev_addr: 0x%2x, reg_addr: 0x%2x, %s", __FUNCTION__, dev_addr, reg_addr, strerror(error));
	} else {
		*data = i2c_data.buf[0];
	}
	return error;
}

/***************************************************************** I2C_WR() ***/
int
i2c_wr(int fd, uint32_t dev_addr, uint8_t reg_addr, uint8_t data)
{
	struct send_recv
	{
		i2c_send_t hdr;
		uint8_t buf[2];
	} i2c_data;

	int error = EOK;

	i2c_data.buf[0] = reg_addr;
	i2c_data.buf[1] = data;
	i2c_data.hdr.len = 2;
	i2c_data.hdr.slave.addr = dev_addr;
	i2c_data.hdr.slave.fmt = I2C_ADDRFMT_7BIT;
	i2c_data.hdr.stop = 1;

	error = devctl(fd, DCMD_I2C_SEND, &i2c_data, sizeof (i2c_data), NULL);
	if(error != EOK) {
		logmsg( "%s failed,  dev_addr: 0x%2x, reg_addr: 0x%2x, %s", __FUNCTION__, dev_addr, reg_addr, strerror(error));
	}
	return error;
}

int i2c_dumper(int32_t i2c_fd, uint32_t slave_addr,
		uint32_t start , uint32_t count){

	uint8_t tmp;
	uint32_t stride = 0x10;
	uint32_t i = 0;
	int32_t ret = -1;
	printf("      0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F	\n");
	for(i = start ; i < count + 1 ; i++){
		if(i % stride == 0){
		   printf(" %02X:",i);
		}
		ret = i2c_rd(i2c_fd, slave_addr, i, &tmp);
		if(ret == -1){
			printf("Failed to dump reg 0x%x.\n",i);
			return(-1);
		}
		printf(" %02X",tmp);
		if((i != 0) && ((i+1) % stride == 0)){
		   printf(" \n");
		}
	}
    printf(" \n");
    return 0;
}
